//
//  GHNetworkManager+Extension.swift
//  GHWeibo
//
//  Created by LGH on 2017/8/14.
//  Copyright © 2017年 LGH. All rights reserved.
//

import Foundation

extension GHNetworkManager {
    
    /// 封装微博请求方法
    ///
    /// - Parameters:
    ///   - since_id: 下拉刷新id，最晚一条微博的id，默认为0
    ///   - max_id: 上拉刷新id，最早一条微博的id，默认为0
    ///   - completion: 完成回调
    func loadStatusData(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping ([[String: Any]]?, Bool)->() ) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //对max_id减一操作，因为微博会返回 小与等于max_id的微博，会导致最后一条数据重复
        let maxid = (max_id > 0) ? (max_id - 1) : 0
        let params = ["since_id": "\(since_id)", "max_id": "\(maxid)"]
        tokenRequest(method: .GET, URLString: urlString, parameters: params) { (json, isSuccess) in
            if isSuccess {
                
                if let data = json as? [String: Any] {
                    
                    let statuses = data["statuses"] as? [[String: Any]]
                    completion(statuses, isSuccess)
                }
            }
        }
    }
    
    func getAccessToken(code: String) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parames = ["client_id":GHAppKey,
                       "client_secret":GHAppSecret,
                       "grant_type":"authorization_code",
                       "code":code,
                       "redirect_uri":GHRedirectURI]
        request(method: .POST, URLString: urlString, parameters: parames) { (json, isSuccess) in
            print(json!)
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
            print("userAccount = \(self.userAccount)")
        }
    }
}
